/*
	Copyright (C) 2011 Daniel C. Dennison (dandennison84@gmail.com).  All rights reserved.
	This file is licensed under the EPL 1.0 (Eclipse Public License 1.0)
	A copy of the license can be found at http://www.eclipse.org/legal/epl-v10.html
*/

package com.gmail.dandennison84.accounting


class JournalEntry {
	int id
	Date dateTime
	String description
	boolean posted
	List<JournalEntryAmount> debits = []
	List<JournalEntryAmount> credits = []

	double balance() {
		double debitSum = debits.inject(0) {acc, val -> acc + val.amount}
		double creditSum = credits.inject(0) {acc, val -> acc + val.amount}
		debitSum - creditSum
	}

	JournalEntryAmount findDebitAccountByName(String name) {
		debits.find {it.account.name == name}
	}

	double findDebitAmountByName(String name) {
		JournalEntryAmount jea = findDebitAccountByName(name)
		jea != null ? jea.amount : 0.0
	}

	JournalEntryAmount findCreditAccountByName(String name) {
		credits.find {it.account.name == name}
	}

	double findCreditAmountByName(String name) {
		JournalEntryAmount jea = findCreditAccountByName(name)
		jea != null ? jea.amount : 0.0
	}

	void post() {
		if(!posted) {
			debits.each {it.account.entries.add(this)}
			credits.each {it.account.entries.add(this)}
			posted = true
		}
	}
}
